package com.jic.manager.impl;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.IDUtils;
import com.jic.manager.entity.*;
import com.jic.manager.enums.CertificateType;
import com.jic.manager.enums.SysUserStatusEnums;
import com.jic.manager.enums.SysUserTypeEnums;
import com.jic.manager.mapper.MerchantMapper;
import com.jic.manager.mapper.SysRoleUserMapper;
import com.jic.manager.request.CertificateRequest;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.request.SaveDeptListRequest;
import com.jic.manager.request.SaveDeptListRequestList;
import com.jic.manager.response.MemMerchantInfoResponse;
import com.jic.manager.response.MerchantResponse;
import com.jic.manager.service.CertificateService;
import com.jic.manager.service.MerchantService;
import com.jic.manager.service.SysDeptService;
import com.jic.manager.service.SysUserService;
import com.jic.manager.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//import org.springframework.stereotype.Service;

/**
 * 商家表
 * @author :
 * @email :
 * @since : 2020-02-26 09:40:44
 * @version : v1.0.0
 */
@Component
@Slf4j
public class MerchantServiceImpl implements MerchantService{

    @Resource
    private MerchantMapper merchantMapper;
    @Resource
    private CertificateService certificateService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;


    @Override
    public long insert(Merchant merchant) {
        long flag = merchantMapper.insert(merchant);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return merchantMapper.delete(id);
    }

    @Override
    public long update(Merchant merchant) {
        return merchantMapper.update(merchant);
    }

    @Override
    public Merchant queryByPrimaryKey(Long id){
        return merchantMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<Merchant> query(Merchant merchant){
        return merchantMapper.query(merchant);
    }

    @Override
    public PageResult<Merchant> queryPage(Merchant merchant, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<Merchant> list = merchantMapper.queryPage(startIndex, pageQuery.getLimit(), merchant);
        long count = merchantMapper.queryPageCount(merchant);
        PageResult<Merchant> pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> editMerchantInfo(MerchantRequest merchantRequest) {
        try {

            Merchant merchant = new Merchant();
            BeanUtils.copyProperties(merchantRequest,merchant);
            Long id = merchant.getId();
            if (id != null && id != 0) {
                merchantMapper.update(merchant);
            } else {
                //新增机构 ， 账号（账号状态 待审核）
                List<Merchant> merchantList = merchantMapper.query(new Merchant() {{
                    setName(merchant.getName());
                }});
                if (CollectionUtils.isNotEmpty(merchantList)) {
                    throw new RuntimeException("商家名称已存在,请重新输入");
                }

                //判断账号是否存在
                List<SysUser> userList = sysUserService.query(new SysUser() {{
                    setAccount(merchantRequest.getAccount());
                    setDeleteFlag(0);
                }});
                if(CollectionUtils.isNotEmpty(userList)){
                    return RestResult.error("9999","账号已存在");
                }
                //账号
                Long userId = sysUserService.insertSysUser(new SysUser() {{
                    setAccount(merchantRequest.getAccount());
                    setPassword(merchantRequest.getPassword());
                    setMobile(merchantRequest.getContactMobile());
                    setUsername(merchantRequest.getContactName());
                    setRoleid(merchantRequest.getRoleId());
                    setStatus(SysUserStatusEnums.PENDING.getName());
                    setType(SysUserTypeEnums.MERCHANT_USER.getName());
                    setCreateTime(new Date());
                    setCreator(merchantRequest.getAdminOperate().getOperator());
                    setDeleteFlag(0);
                }});

                sysRoleUserMapper.insert(new SysRoleUser(){{
                    setRoleid(merchantRequest.getRoleId());
                    setUserid(userId);
                    setStatus("0");
                }});
                //新增
                merchant.setStatus(1);
                merchant.setUserId(userId);
                merchant.setUserName(merchantRequest.getAccount());
                merchant.setCreator(merchantRequest.getAdminOperate().getOperator());
                merchantMapper.insert(merchant);
            }
            return RestResult.success("成功");
        } catch (Exception e) {
            log.error("error",e);
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }

    @Override
    public RestResult<String> merchantsSettled(MerchantRequest merchantRequest) throws Exception {
        List<CertificateRequest> mCertificateVos = merchantRequest.getMCertificateList();
        Merchant mMerchant = new Merchant();
        BeanUtils.copyProperties(merchantRequest,mMerchant);
        //新增资质文件
        if (CollectionUtils.isEmpty(mCertificateVos)) {
            throw new RuntimeException("资质文件未添加");
        }
        if (merchantRequest.getId() != null && merchantRequest.getId() != 0){
            //删除资质证书
            certificateService.deleteListByTypeAndOrgId(new Certificate(){{
                setCertificateType(CertificateType.certifications_type.getName());
                setMerchantId(mMerchant.getId());
            }});
            //修改
            merchantMapper.update(mMerchant);
        }else{
            //新增机构 ， 账号（账号状态 待审核）
            List<SysDept> sysDepts = sysDeptService.query(new SysDept() {{
                setDeptName(merchantRequest.getName());
            }});
            if (CollectionUtils.isNotEmpty(sysDepts)) {
                throw new RuntimeException("商家名称已存在,请重新输入");
            }
            //账号
            String account = merchantRequest.getAccount();
            String passWord = merchantRequest.getPassword();
            if (StringUtils.isEmpty(account) || StringUtils.isEmpty(passWord)) {
                throw new RuntimeException("账号,密码不能为空");
            }
            List<SysUser> sysUsers = sysUserService.query(new SysUser() {{
                setAccount(account);
            }});
            if (CollectionUtils.isNotEmpty(sysUsers)) {
                throw new RuntimeException("账号已存在,请重新输入");
            }

            //新增
            mMerchant.setStatus(1);
//            mMerchant.setCreator(0L);
            mMerchant.setCreateTime(new Date());
            mMerchant.setDeleteFlag(0);
            merchantMapper.insert(mMerchant);

            SysDept sysDept = new SysDept() {{
                setDeptName(merchantRequest.getName());
                setSort(0);
                setCreateTime(new Date());
                setPid(0L);
            }};
            sysDeptService.insert(sysDept);


            String uuid = UuidUtil.getTimeBasedUuid().toString();

            SysUser sysUser = new SysUser() {{
                setAccount(account);
                setPassword(MD5Utils.md5(passWord,uuid));
                setStatus(2);
                setFlag(uuid);
                setType(1);
                setMobile(mMerchant.getContactMobile());
                setUsername(merchantRequest.getName());
                setDeptId(sysDept.getId());
                setLname(mMerchant.getName());
                setCreateTime(new Date());
                setDeleteFlag(0);
            }};
            sysUserService.insert(sysUser);
            //更新用户主账号
            merchantMapper.update(new Merchant(){{
                setUserId(sysUser.getId());
                setUserName(sysUser.getUsername());
                setId(mMerchant.getId());
            }});
        }
        mCertificateVos.stream().forEach(mCertificateVo -> {
            mCertificateVo.setMerchantId(mMerchant.getId());
            mCertificateVo.setIsAvailable(1);
            mCertificateVo.setCertificateType(CertificateType.certifications_type.getName());
        });
        certificateService.insertMCertificateList(mCertificateVos);
        return RestResult.success("入驻成功");
    }

    @Override
    public MemMerchantInfoResponse getShopList(Long merchantId) {
        return merchantMapper.getShopList(merchantId);
    }
    /*
     * 商家列表查询
     * */
    @Override
    public PageResult<Merchant> queryMerchantPage(Merchant merchant, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<Merchant> list = merchantMapper.queryPageMerchant(startIndex, pageQuery.getLimit(), merchant);
        long count = merchantMapper.queryPageMerchantCount(merchant);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    /*
     * 导入方法
     * */
    @Override
    public RestResult importMerchantInfo(List<MerchantRequest> merchantList) {
        Merchant merchant = new Merchant();
        SaveDeptListRequest saveDeptListRequest= new SaveDeptListRequest();
        List<SaveDeptListRequestList> saveList = new ArrayList();
        for (int i = 0; i <merchantList.size();i++ ){
            //判断第三方商家编码是否重复
            Merchant merchantQuery = new Merchant();
            merchantQuery.setThirdMerchantCode(merchantList.get(i).getOrgNumber());
            List<Merchant> merchantlist = this.query(merchantQuery);
            if (merchantlist.size()>0){
                return RestResult.error("9999","商家编码不可重复请检查！");
            }
            //
            BeanUtils.copyProperties(merchantList.get(i),merchant);
            merchant.setThirdMerchantCode(merchantList.get(i).getOrgNumber());
            merchant.setDeleteFlag(0);
            merchant.setMerchantStatus(1L);
            merchant.setDeptId(1L);
            merchant.setCreator(1L);
            merchant.setChildId(merchantList.get(i).getChildId());
            merchantMapper.insert(merchant);
            //组装sys_dept 数据
            SaveDeptListRequestList saveDeptListRequestList = new SaveDeptListRequestList();
            saveDeptListRequestList.setBusinessId(merchant.getId());
            saveDeptListRequestList.setDeptName(merchantList.get(i).getName());
            saveList.add(saveDeptListRequestList);
            //子平台id
            saveDeptListRequest.setPBusinessId(merchantList.get(i).getChildId());
        }
        //所属层级
        saveDeptListRequest.setDeptType(2);
        saveDeptListRequest.setSaveDeptListRequestListList(saveList);
        sysDeptService.saveDeptList(saveDeptListRequest);
        return RestResult.success(1);
    }

    @Override
    public RestResult<List<MerchantRequest>> queryMerchantListByid(List<Long> merchantList) {
        List<Merchant> list = merchantMapper.queryMerchantListByid(merchantList);
        List<MerchantRequest> collect = list.stream().map(x -> {
            MerchantRequest response = new MerchantRequest();
            BeanUtils.copyProperties(x, response);
            return response;
        }).collect(Collectors.toList());
        RestResult result = new RestResult();
        result.setData(collect);
        return result;
    }

    @Override
    public RestResult<Merchant> getByThirdMerchantCode(String code) {
        Merchant merchant = merchantMapper.getByThirdMerchantCode(code);
        return RestResult.success(merchant);
    }

    @Override
    public RestResult importMerchantInfoByExcel(MultipartFile multipartFile,Long childcode) throws IOException {
        List<Integer> failRows = new ArrayList<>();//失败行数汇总
        List<Integer> repeatRows = new ArrayList<>();//重复行数汇总
        //转化成workBook对象
        Workbook workBook = WorkBookUtil.createWorkBook(multipartFile.getInputStream(), ExcelTypeEnum.XLS);
        Sheet sheet = workBook.getSheetAt(0);//获取第一个工作表
        int rowCount = sheet.getLastRowNum() + 1;//获取总行数
        SaveDeptListRequest saveDeptListRequest= new SaveDeptListRequest();
        List<SaveDeptListRequestList> saveList = new ArrayList();
        for (int i = 1; i < rowCount; i++) {
            try {
                Row row = sheet.getRow(i);
                Merchant merchant = createMerchant(row);
                try {
                    if (merchant != null) {
                        //插入上级组织id
                        merchant.setChildId(childcode);
                        //生成商家编码（自己）
                        merchant.setOrgNumber(IDUtils.GenerateBillNo());
                        //判断第三方商家编码是否重复
                        Merchant merchantQuery = new Merchant(){{
                            setThirdMerchantCode(merchant.getThirdMerchantCode());
                        }};
                        List<Merchant> merchantlist = this.query(merchantQuery);
                        if (merchantlist.size()>0){
                            return RestResult.error("9999","商家编码不可重复请检查！");
                        }

                        this.insert(merchant);
                        //组装sys_dept 数据
                        SaveDeptListRequestList saveDeptListRequestList = new SaveDeptListRequestList();
                        saveDeptListRequestList.setBusinessId(merchant.getId());
                        saveDeptListRequestList.setDeptName(merchant.getName());
                        saveList.add(saveDeptListRequestList);
                        //子平台id
                        saveDeptListRequest.setPBusinessId(childcode);
                    } else {
                        failRows.add(new Integer(i+1));
                        continue;
                    }
                } catch (Exception e) {
                    repeatRows.add(new Integer(i + 1));
                }
            } catch (Exception e) {
                // 记录异常数据的行号
                failRows.add(new Integer(i + 1));
            }
        }
        //所属层级
        saveDeptListRequest.setDeptType(2);
        saveDeptListRequest.setSaveDeptListRequestListList(saveList);
        sysDeptService.saveDeptList(saveDeptListRequest);

        return RestResult.success(1);
    }

    @Override
    public List<Merchant> queryMerchantPageOther(Merchant merchant) {
        List <Merchant> merchantList = merchantMapper.queryMerchantPageOther(merchant);
        return merchantList;
    }

    private Merchant createMerchant(Row row) {
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        Merchant merchant = new Merchant();
        //获取商家编码
        merchant.setThirdMerchantCode(row.getCell(0).getStringCellValue());
        //获取商家名称
        merchant.setName(row.getCell(1).getStringCellValue());
        //商家所属省
        merchant.setRegisteredProvinceId(row.getCell(2).getStringCellValue());
        //商家所属市
        merchant.setRegisteredCityId(row.getCell(3).getStringCellValue());
        //商家所属区
        merchant.setRegisteredRegionId(row.getCell(4).getStringCellValue());
        //商家详细地址
        merchant.setRegisteredDetailAddress(row.getCell(5).getStringCellValue());
        if (row.getCell(6).getStringCellValue().equals("自营商家")) {
            merchant.setMerchantType("1");
        } else {
            merchant.setMerchantType("2");
        }
        //商家联系人
        merchant.setContactName(row.getCell(7).getStringCellValue());
        //手机号
        Cell mobile = row.getCell(8);
        if (CellType.STRING == mobile.getCellTypeEnum()) {
            merchant.setContactMobile(row.getCell(8).getStringCellValue());//第三方店铺编码字符串类型
        } else {
           merchant.setContactMobile(decimalFormat.format(row.getCell(8).getNumericCellValue()));
        }
        merchant.setMerchantStatus(1L);
        merchant.setCreateTime(new Date());
        merchant.setDeleteFlag(1);
        return merchant;
    }


    /*查询商家适用范围*/
    public MemMerchantInfoResponse getGrowhtScopeInfo (Long merchantId) {
        MemMerchantInfoResponse memMerchantInfoResponse = merchantMapper.getGrowhtScopeInfo(merchantId);
        return memMerchantInfoResponse;
    }

    @Override
    public List<MerchantResponse> queryBySelect(MerchantRequest merchant) {
        Merchant query = new Merchant();
        BeanUtils.copyProperties(merchant, query);
        return merchantMapper.query(query).stream().map(x->{
            MerchantResponse response = new MerchantResponse();
            BeanUtils.copyProperties(x, response);
            return response;
        }).collect(Collectors.toList());
    }


    @Override
    public List<MemMerchantInfoResponse> getMerchantList(List<Long> deptIds) {
        return merchantMapper.getMerchantList(deptIds);
    }

    @Override
    public List<JSONObject> getMerchantToSett() {
        return merchantMapper.getMerchantToSett();
    }
}
